<template>
    <el-row>
        <el-col :span="24">
            <el-card>
                <el-row :gutter="24">
                    <!-- 添加房型 -->
                    <el-col :span="12" :offset="0"><el-button type="primary" style="margin-left: 10px"
                            @click="drawer = true">
                            新增房型
                        </el-button>
                        <el-button type="danger" @click="BatchDelRoom()">批量删除</el-button>
                        <el-drawer v-model="drawer" title="I am the title" :with-header="false">
                            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules"
                                label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                                <el-form-item label="房型名称" prop="rtname">
                                    <el-input v-model="ruleForm.rtname" />
                                </el-form-item>
                                <el-form-item label="门市价" prop="rprice">
                                    <el-input v-model="ruleForm.rprice" />
                                </el-form-item>
                                <el-form-item label="押金" prop="deposit">
                                    <el-input v-model="ruleForm.deposit" />
                                </el-form-item>
                                <el-form-item label="房型面积" prop="rarea">
                                    <el-input v-model="ruleForm.rarea" />
                                </el-form-item>
                                <el-form-item label="可住人数" prop="roccupancy">
                                    <el-input v-model="ruleForm.roccupancy" />
                                </el-form-item>
                                <el-form-item label="房型图片" prop="rpicture">
                                    <el-upload class="avatar-uploader"
                                        action="http://localhost:5199/api/RoomType/UpdFile" :show-file-list="false"
                                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                        :multiple="true">
                                        <img v-if="ruleForm.rpicture"
                                            :src="'http://localhost:5199/pic/' + ruleForm.rpicture" class="avatar" />
                                        <el-icon v-else class="avatar-uploader-icon">
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="房型介绍" prop="rdescription">
                                    <el-input v-model="ruleForm.rdescription" type="textarea" />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                                        确认
                                    </el-button>
                                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                                </el-form-item>
                            </el-form>
                        </el-drawer></el-col>
                    <el-col :span="12" :offset="0">
                        <el-form :inline="true" :model="seachData" class="demo-form-inline">
                            <el-form-item>
                                <el-input v-model="seachData.rtname" placeholder="房型名称" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="GetRoomTypeList">查询</el-button>
                            </el-form-item>
                        </el-form></el-col>
                </el-row>
            </el-card>
        </el-col>
    </el-row>
    <!-- 房型显示 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="Rtname" label="房型名称" align="center" />
        <el-table-column prop="Rprice" label="门市价（元）" align="center">
            <template v-slot="scope">
                ￥<span>{{ scope.row.Rprice }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="Deposit" label="押金（元）" align="center">
            <template v-slot="scope">
                ￥<span>{{ scope.row.Deposit }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="RoomCount" label="房间数量" align="center" />
        <el-table-column prop="Rsort" label="排序" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center">
            <template v-slot="scope">
                <el-link type="primary" @click="DelRoom(scope.row.Rtid)">删除</el-link>&nbsp;&nbsp;
                <el-link type="primary" @click="FindRoomType(scope.row.Rtid)">编辑</el-link>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <table style="margin:0 auto">
        <tr>
            <td>
                <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :page-sizes="[2, 4, 6, 8]"
                    :small="small" :background="background" layout="total,slot,scop, sizes" :total="totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <span>，共计{{ pageCount }}页，当前{{ pageIndex }}/{{ pageCount }}页</span>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :page-sizes="[2, 4, 6, 8]"
                    :small="small" :background="background" layout="slot, prev, pager, next" :total="totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <button @click="handleCurrentChange(1)" :disabled="pageIndex === 1" class="btn-prev">首页</button>
                </el-pagination>
            </td>
            <td>
                <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :page-sizes="[2, 4, 6, 8]"
                    :small="small" :background="background" layout="slot, jumper" :total="totalCount"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                    next-text="下一页">
                    <button @click="handleCurrentChange(pageCount)" :disabled="pageIndex === pageCount"
                        class="btn-prev">尾页</button>
                </el-pagination>
            </td>
        </tr>
    </table>

    <!-- 修改房型开始 -->
    <el-drawer v-model="dialogFormVisible" title="I am the title" :with-header="false">
        <el-form style="max-width: 600px" :model="from" label-width="auto" class="demo-ruleForm" :size="formSize"
            status-icon>
            <el-form-item label="房型名称">
                <el-input v-model="from.Rtname" />
            </el-form-item>
            <el-form-item label="门市价" prop="rprice">
                <el-input v-model="from.Rprice" />
            </el-form-item>
            <el-form-item label="押金" prop="deposit">
                <el-input v-model="from.Deposit" />
            </el-form-item>
            <el-form-item label="房型面积">
                <el-input v-model="from.Rarea" />
            </el-form-item>
            <el-form-item label="可住人数">
                <el-input v-model="from.Roccupancy" />
            </el-form-item>
            <el-form-item label="排序">
                <el-input v-model="from.Rsort" />
            </el-form-item>
            <el-form-item label="房型图片" prop="rpicture">
                <el-upload class="avatar-uploader" action="http://localhost:5199/api/RoomType/UpdFile"
                    :show-file-list="true" :on-success="handleAvatarSuccess">
                    <img v-if="from.Rpicture" :src="'http://localhost:5199/pic/' + from.Rpicture" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="房型介绍">
                <el-input v-model="from.Rdescription" type="textarea" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="UpdRoomInfo()">
                    修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
    <!-- 修改房型结束 -->
</template>
<script setup lang="ts">

import axios from 'axios';
const drawer = ref(false)
import type { FormInstance, FormRules } from 'element-plus'

import { reactive, ref, onMounted } from 'vue'


axios.defaults.baseURL = 'http://localhost:5199/api/';

import { Plus } from '@element-plus/icons-vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import type { UploadProps } from 'element-plus'

const dialogFormVisible = ref(false);

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
//修改房型数据
interface IRuleForm {
    Rtid: number,
    Rtname: string,
    Rprice: number,
    Deposit: number,
    Rarea: number,
    Roccupancy: number,
    //RoomCount: number,
    Rsort: number,
    Rpicture: string,
    Rdescription: string,
    //TenantId: string
}
const from = ref<IRuleForm>({
})

//添加房型数据
const ruleForm = reactive({
    rtname: "",
    rprice: "",
    deposit: "",
    rarea: "",
    roccupancy: "",
    rpicture: "",
    rdescription: "",
})

/* 查询条件 */
const seachData = reactive({
    rtname: "",
})

//分页数据
const pageIndex = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const pageCount = ref(0);


const small = ref(false)
const background = ref(false)

const tableData = ref([]);// 定义列表

const multipleTableRef = ref([]);


//验证
const rules = reactive<FormRules>({
    rtname: [
        { required: true, message: '请输入房型名称', trigger: 'blur' },
    ],
    rprice: [{ required: true, message: '请输入门市价', trigger: 'blur' }],
    roccupancy: [{ required: true, message: '请输入可住人数', trigger: 'blur' }],
    rdescription: [{ required: true, message: '请输入房型介绍', trigger: 'blur' }],
})


//图片上传成功后
const handleAvatarSuccess = (UrlPic: string) => {
    ruleForm.rpicture = UrlPic;
}

//图片格式验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rpicture) => {
    if (rpicture.type == 'png/jpg') {
        ElMessage.error('图片上传成功!')
        return false
    } else if (rpicture.size / 1024 / 1024 > 5) {
        ElMessage.error('图片上传大小不能超过5M!')
        return false
    }
    return true
}

//添加房型
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post(`RoomType/RoomTypeAdd`, ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success("房型添加成功");
                    drawer.value = false;
                    GetRoomTypeList();
                }
                else {
                    ElMessage.error("房型名称已有，请重新添加");
                }
            })

        } else {
            console.log('error submit!', fields)
        }

    })
}

//删除房型
const DelRoom = (Rtid) => {
    ElMessageBox.confirm(
        '确认删除房型吗?',
        '房型删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            axios.delete(`RoomType/DeleteRoomType?rtid=${Rtid}`).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Msg);
                    GetRoomTypeList();
                }
                else {
                    ElMessage.warning(res.data.Msg);
                    return;
                }
            })
        })
        .catch(() => {

        })
}
//批量删除房型
const BatchDelRoom = () => {
    if (multipleTableRef.value.length == 0) {
        ElMessage.warning("至少选择一个要删除的房型");
        return;
    }
    ElMessageBox.confirm(
        '确认删除房型吗?',
        '房型删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            console.log(multipleTableRef.value);
            axios.put("RoomType/BatchDelRoomType", multipleTableRef.value).then(res => {
                console.log(multipleTableRef.value);
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Msg);
                    GetRoomTypeList();
                }
                else {
                    ElMessage.warning(res.data.Msg);
                    return;
                }
            })
        })
        .catch(() => {

        })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//选中的房型
function handleSelectionChange(val: any) {
    multipleTableRef.value = val
}

//房型显示
const GetRoomTypeList = () => {
    axios.get('RoomType/GetRoomTypeList', {
        params: {
            pageIndex: pageIndex.value,
            pageSize: pageSize.value,
            rtname: seachData.rtname,
        }
    }).then((res) => {
        tableData.value = res.data.Data;
        totalCount.value = res.data.TotalCount;
        pageCount.value = res.data.PageCount;
    })
}

const handleSizeChange = (val: number) => {
    pageSize.value = val;
    GetRoomTypeList();
}

const handleCurrentChange = (val: number) => {
    pageIndex.value = val;
    GetRoomTypeList();
}

//房型反填
function FindRoomType(Rtid: number) {
    axios.get(`RoomType/GetFindRoomType?rtid=${Rtid}`).then(res => {
        from.value = res.data.Data;

    })
    dialogFormVisible.value = true;
}

//修改房型
const UpdRoomInfo = () => {
    console.log(from);
    axios.post("RoomType/UpdRoomType", from.value).then(res => {
        if (res.data.Code == 200) {
            ElMessage.success("房型修改成功");
            dialogFormVisible.value = false;
            GetRoomTypeList();
        }
        else {
            ElMessage.error("房型修改失败");
        }
    })
}
//勾子函数
onMounted(() => {
    GetRoomTypeList();
})
</script>

<style scoped>
.avatar-uploader .avatar {
    max-width: 178px;
    max-height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>